<template>
    <div class="form-group inputGroupSearch">
        <label :style="finalLabelStype" :class="labelClass"><span v-if="required" class="required ">*</span>{{ title }}：</label>
        <div :class="rightClass" :style="rightStyle">
            <form-pop :content="error" />
            <a-input-search type="text" class="ant-input-sm" :id="id" :name="name" :value="selectedTitle" :title="selectedTitle" read-only :size="size" enter-button @click="showModal" @search="showModal">
                <a-tooltip slot="suffix" title="点击清除" v-if="clearValueIcon" v-show="selectedTitle">
                    <a-icon type="close" style="color: rgba(0,0,0,.45)" @click="clearValue" />
                </a-tooltip>
            </a-input-search>

            <keep-alive>
                <!-- modal 弹窗  -->
                <a-modal :title="modalTitle" :visible="visible" @cancel="hideModal" width="320px" :bodyStyle="{height:'100'}">

                    <tree-data ref="searchTree" :treeData="treeData" :dataList="dataList" :parentKeys="parentKeys" :checkable="checkable" :treeType="treeType" :selectedKeys.sync="selectedKeys" :parentUpdateValue="updateValue" :keyIncludeObj="keyIncludeObj" :defaultExpandAll="defaultExpandAll"></tree-data>
                    <div slot="footer">
                        <a-button type="primary" @click="onSubmit">确定</a-button>
                    </div>
                </a-modal>
            </keep-alive>
        </div>
    </div>
</template>

<script>
import { InputGroupSearchActions } from "@/mixins/actions";
import formAttr from "@/mixins/form/form-attr";
import TreeData from "@/components/TreeData/TreeData";
import store from "../../store";
// import TreeData from "@/components/TreeData/TreeTest"

const defaultLabelStype =
    "font-weight: normal;justify-content: flex-end;padding-left: 5px;text-align: right;width:110px;";

export default {
    components: { TreeData },
    mixins: [formAttr, InputGroupSearchActions],
    props: {
        valueType: {
            type: String,
            default: "sigle"
        },
        modalTitle: {
            type: String,
            default: "选择"
        },
        checkable: { //是否是搜索（搜索中组件需要用户多选  进行搜索）
            type: Boolean,
            default: false,
        },
        //选择可以
        myKeyIncludeObj: {
            type: Object,
            default: null
        },
        //返回的title
        valueTitle: {
            type: String,
            default: ""
        },
        //是否显示 删除图标
        clearValueIcon: {
            type: Boolean,
            default: true
        },
    },
    data () {
        return {
            selectedKeys: [],
            parentKeys: [],
            treeData: [],
            dataList: [],
            keyIncludeObj: null,
            visible: false,
            defaultExpandAll: false
        };
    },
    created () {
        const { myKeyIncludeObj } = this;
        if (myKeyIncludeObj) {
            Object.assign(this, { keyIncludeObj: myKeyIncludeObj });

        }

        //内部 加载treeData模式
        if (!this.treeData || this.treeData.length == 0) {
            this.CheckTreeData();
        }
        this.selectedKeys = this.initSelectedKeys();
    },
    computed: {
        selectedTitle: function () {
            const { selectedKeys, dataList } = this;
            console.log("搜索选择转换title_selectedKeys", selectedKeys, dataList)

            if (selectedKeys.forEach && dataList.forEach ) {
                const titles = [];
                selectedKeys.forEach(item => {
                    let obj = dataList.find(f => f.key == item);
                    if(obj)titles.push(obj.title);
                });
                console.log("计算属性selectedTitle：", titles, selectedKeys, dataList);
                return titles.join(",");
            }
            return "";
        },
        finalLabelStype: function () {
            return this.labelStyle || defaultLabelStype;
        }
    },
    mounted () { },
    beforeUpdate () {

    },
    updated () { },
    methods: {
        initSelectedKeys () {
            const { value, keyIncludeObj ,checkable } = this;
            console.log("initSelectedKeys: keyIncludeObj", keyIncludeObj, value,checkable)
            if (keyIncludeObj && keyIncludeObj.include) {
              if (value && value.forEach) {
                  value.forEach(item => {
                      item = item + keyIncludeObj.include;
                  });
                  return value;
              } else {
                  if(checkable){
                    let newValue = (value+"").split(",");
                    let newArr = [];
                    console.log("initSelectedKeys: newValue", newValue)
                    newValue.forEach(newItem => {
                        newArr.push(newItem + keyIncludeObj.include);
                    });
                    return newArr;
                  }else{
                    console.log("value + keyIncludeObj.include", value + keyIncludeObj.include);
                    return [value + keyIncludeObj.include];
                  }
                }
            }
            return [value];
        },
        showModal () {
            const { treeType, treeData } = this;
            // if ("areaTree" == treeType && treeData.length == 0) {
            //     let _this = this;
            //     let isHaveRight = store.getters.permissions.includes("sys:area");
            //     let message = "请联系管理员进行‘区域配置’";
            //     let okText = "确定";
            //     let cancelText = "关闭";
            //     if (isHaveRight) {
            //         message = "没有配置地区数据,是否现在配置";
            //         okText = "马上配置";
            //         cancelText = "稍后配置";
            //     }
            //     this.$confirm({
            //         title: '提示',
            //         content: <span>{message}</span>,
            //         okText,
            //         cancelText,
            //         onOk () {
            //             if (isHaveRight) {
            //                 console.log("准备进入地区配置页面。。。",)
            //                 // _this.$router.push("/system/area/list");
            //                 window.location.replace("/system/area/list");
            //             }
            //         },
            //         onCancel () {
            //             console.log("没有地区数据，" + cancelText)
            //         },
            //     });
            // } else {
                this.visible = true;
                this.selectedKeys = [];
            // }


        },
        hideModal () {
            this.visible = false;
            console.log(
                "inputGroup_.selectedKeys",
                this.selectedKeys,
                this.selectedTitle
            );
        },
        onSubmit () {
            this.$refs.searchTree.onSubmit();

            this.updateValue();
        },
        updateValue () {
          const { treeType } = this;
            let values = null;
            console.log(this.selectedKeys);
            switch (this.valueType) {
                case "sigle":
                    values = (this.checkable && "officeUser" == treeType) ? this.selectedKeys : this.selectedKeys[0];
                    break;
            }
            if (values) {
                let checkResult = this.checkRightKey(values);
                if (!checkResult) return false;
                values = checkResult;
            }

            // console.log("更新的values",values)
            this.$emit("input", values);   //更新 v-model 绑定的值
            this.$emit("update:valueTitle", this.selectedTitle);
            this.hideModal();
        },
        //清除
        clearValue () {
            this.$emit("input", null);    //更新 v-model 绑定的值
            this.$emit("update:valueTitle", "");
            this.hideModal();
        },
        checkRightKey (value) {
            const { keyIncludeObj } = this;
            console.log("keyIncludeObj", keyIncludeObj);
            
            if (keyIncludeObj && keyIncludeObj.include) {
                let include = keyIncludeObj.include;

                if (value && value.forEach) {
                    let v = [];
                    value.forEach(item => {
                        v.push(item.replace(include, ""));
                    });
                    let joinVal = v.join(",");
                    console.log("替换后的value", joinVal)
                    return joinVal;
                } else {
                    if (value.indexOf(include) === -1) {
                        this.$message.warn(keyIncludeObj.message || "请选择正确的选项");
                        this.selectedKeys = [];
                        return "";
                    } else {
                        value = value.replace(include, "");
                        console.log("替换后的value", value)
                        return value;
                    }
                }

            }
            return value;
        },
        //tree ==> list  树结构 转 list结构
        generateList (data) {
            for (let i = 0; i < data.length; i++) {
                const node = data[i];
                const key = node.key;
                const title = node.title;
                if (node.children) {
                    this.generateList(node.children);
                    this.parentKeys.push(key);
                    this.dataList.push({ key, title, isParent: true });
                } else {
                    this.dataList.push({ key, title });
                }
            }
        },
        //查找 显示的标题名称(弃用)
        findTitle () {
            console.log(
                "findTitle",
                this.selectedTitle,
                this.selectedKeys,
                this.dataList
            );
            if (
                !this.selectedTitle &&
                this.selectedKeys.length > 0 &&
                this.dataList.length > 0
            ) {
                const titles = [];
                console.log("titles_111", titles);
                let i = 0;
                let size = this.selectedKeys.length;
                this.dataList.forEach(f => {
                    if (f.key == this.selectedKeys[i]) {
                        titles.push(f.title);
                        i++;
                        if (i >= size) return false;
                    }
                });
                console.log("titles__2", titles);
                return titles.join(",");
                //
            }
        }
    },

    watch: {
        treeData: function (newVal, oldVal) {
            console.log("选择搜索_treeData——改变", newVal, oldVal)
            // this.findTitle();
        },
        value: function (n, o) {
            console.log("选择搜索_value_改变", n, o)
            this.selectedKeys = this.initSelectedKeys();
        }
    }
};
</script>

<style lang="less">
    .inputGroupSearch {
        .input-group {
            cursor: pointer;
        }
        .ant-input-group-wrapper-sm {
            padding: 0 !important;
        }
        .ant-input-affix-wrapper .ant-input-suffix {
            right: 5px;
        }
        .ant-input-group-addon {
            .ant-input-search-button {
                height: 28px;
            }
        }
        .ant-input-group-addon{
            .ant-input-search-button{
                height: 32px;
            }
        }
    }
</style>
